package nj.yb.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    // 全局唯一的SqlSessionFactory
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 读取MyBatis配置文件
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException("MyBatis初始化失败", e);
        }
    }

    /**
     * 获取SqlSession（手动管理生命周期，不自动关闭）
     */

    public static SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit); // true：自动提交事务
    }

    /**
     * 获取Mapper接口实例（不自动关闭SqlSession）
     */
    public static <T> T getMapper(Class<T> mapperClass) {
        // 注意：这里不再使用try-with-resources，避免SqlSession被自动关闭
        SqlSession session = getSqlSession(true);
        return session.getMapper(mapperClass);
    }


}
